﻿using DevExpress.Mvvm;
using DevExpress.Mvvm.Native;
using HandyControl.Controls;
using HandyControl.Data;
using PlaceOrder_Admin.Helper;
using PlaceOrder_Admin.Models.Common;
using PlaceOrder_Core.Helper;
using PlaceOrder_Core.Models.QuanYi;
using PlaceOrder_Core.PlaceOrderModels;
using PlaceOrder_Core.Services.Instances;
using PlaceOrder_Core.Services.Interfaces;
using Prism.DryIoc;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Media;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Input;
using BindableBase = Prism.Mvvm.BindableBase;
using KeyEventArgs = System.Windows.Input.KeyEventArgs;
namespace PlaceOrder_Admin.ViewModels
{
    public class ChatAdminWindowViewModel : BindableBase
    {
        private readonly string _id = Guid.NewGuid().ToString();

        #region 依赖属性
        public ObservableCollection<string> QuickReplies { get; } //快捷回复
        private string chatString;

        public string ChatString
        {
            get { return chatString; }
            set { chatString = value; RaisePropertyChanged(); }
        }

        private string chatTitle;

        public string ChatTitle
        {
            get { return chatTitle; }
            set { chatTitle = value; RaisePropertyChanged(); }
        }


        private bool hasNewMessage = true;

        public bool HasNewMessage
        {
            get { return hasNewMessage = true; }
            set { hasNewMessage = value; RaisePropertyChanged(); }
        }

        #endregion
        public ObservableCollection<ChatInfoModel> ChatInfos { get; set; } = new();


        #region 命令
        public DelegateCommand SendStringCmd => new(SendString);
        public DelegateCommand<RoutedEventArgs> ReadMessageCmd => new(ReadMessage);

        private string selectedReply;

        public string SelectedReply
        {
            get { return selectedReply; }
            set { selectedReply = value; RaisePropertyChanged(); }
        }


        #endregion
        private IDailyData _dailyData { get; set; }
        public ChatAdminWindowViewModel(IDailyData dailyData, string title = "")
        {
            this.ChatTitle = title;
            _dailyData = dailyData;
            QuickReplies = new ObservableCollection<string>
        {
            "好的，麻烦~",
            "收到",
            "谢谢！麻烦了",
            "打错了，撤回上一条消息，不好意思。",
            "请问上一笔成交了吗？",
            "稍等，我思考一下",
            "不改，保持原价"
        };
            Messenger.Default.Register<string>(this, MessageToken.SendChatMessage, ReceiveTitleMessage);

            //Messenger.Default.Register<List<ChatMessage>>(this, MessageToken.SendChatMessage, ReceiveMessageList);
            Messenger.Default.Register<List<ChatMessage>>(this, MessageToken.SendChatMessage, async (messages) =>
            {
                await ReceiveMessageListAsync(messages);
            });
            //Messenger.Default.Register<ChatMessage>(this, MessageToken.NewChatMessageIn, ReceiveNewChatMessage);
            Messenger.Default.Register<string>(this, MessageToken.ClearChatWindow, _ => ClearMessages());

            InitChatMessages();
        }

        /// <summary>
        /// 初始化聊天消息
        /// </summary>
        private void InitChatMessages()
        {
            if (string.IsNullOrEmpty(ChatTitle))
            {
                AppLog.WriteError("ChatTitle为空，有问题");
                return;
            }
            int brokerId = (int)IndexAdminViewModel.Receivers.Where(o => o.Company == ChatTitle).FirstOrDefault().Brokerid;
            List<ChatMessage> tempMessageList = new List<ChatMessage>();
            tempMessageList = _dailyData.GetAllMessageDataByBrokerId(brokerId, 0);
            // 通知滚动到列表底部
            // 在后台线程上执行耗时操作
            var chatInfoModels = tempMessageList.Select(chatMessage => new ChatInfoModel
            {
                Message = chatMessage.ChatMessageInfo,
                Type = ChatMessageType.String,  // Assuming all messages are of type string
                Role = chatMessage.Direction == 0 ? ChatRoleType.Sender : ChatRoleType.Receiver,
                NickName = chatMessage.Direction == 0 ? UserHelper.NickName : ChatTitle,  // This may need to be adjusted based on your logic
                CreateTime = chatMessage.CreateTime ?? DateTime.Now,
                Direction = chatMessage.Direction == 0 ? "0" : "1"
            }).ToList();

            // 在UI线程上更新UI
            foreach (var item in chatInfoModels)
            {
                ChatInfos.Add(item);
            }

            // 通知滚动到列表底部
            ScrollToBottomRequested?.Invoke(this, EventArgs.Empty);
        }

        private void ClearMessages()
        {
            //this.ChatInfos.Clear();
        }


        public void ScrollToBottom()
        {
            ScrollToBottomRequested?.Invoke(this, EventArgs.Empty);
        }
        /// <summary>
        /// 收到一组消息
        /// </summary>
        /// <param name="list"></param>
        /// 

        private async Task ReceiveMessageListAsync(List<ChatMessage> list)
        {
            if (list == null || list.Count == 0)
            {
                Growl.InfoGlobal("当前无该中介消息");
                ChatInfos.Clear();
                return;
            }
            HasNewMessage = true;
            // 在后台线程上执行耗时操作
            var chatInfoModels = await Task.Run(() =>
                list.Select(chatMessage => new ChatInfoModel
                {
                    Message = chatMessage.ChatMessageInfo,
                    Type = ChatMessageType.String,  // Assuming all messages are of type string
                    Role = chatMessage.Direction == 0 ? ChatRoleType.Sender : ChatRoleType.Receiver,
                    NickName = chatMessage.Direction == 0 ? UserHelper.NickName : ChatTitle,  // This may need to be adjusted based on your logic
                    CreateTime = chatMessage.CreateTime ?? DateTime.Now,
                    Direction = chatMessage.Direction == 0 ? "0" : "1"
                }).ToList()
            );

            // 检查brokerName
            string brokerName = IndexAdminViewModel.Receivers
                .Where(o => o.Brokerid == list[0].BrokerId)
                .FirstOrDefault()?.Company;

            if (brokerName == null)
            {
                return;
            }

            // 在UI线程上更新UI
            await PrismApplication.Current.Dispatcher.InvokeAsync(() =>
            {
                foreach (var item in chatInfoModels)
                {
                    ChatInfos.Add(item);
                }
            });

            // 通知滚动到列表底部
            ScrollToBottomRequested?.Invoke(this, EventArgs.Empty);

            SoundPlayerHelper.PlayNotificationSound();
        }

       
        public event EventHandler ScrollToBottomRequested;




        private void ReceiveNewChatMessage(ChatMessage message)
        {

        }



        #region 具体实现
        private void ReceiveTitleMessage(string title)
        {
            // this.ChatTitle = title;
        }

        public int index = 0;
        private System.Timers.Timer _timer;
   


        private void SendString()
        {
            try
            {
                if (string.IsNullOrEmpty(SelectedReply))
                {
                    Growl.InfoGlobal("回复消息为空，请检查");
                    return;
                }
                if (string.IsNullOrEmpty(ChatTitle)) return;
                int brokerId = (int)IndexAdminViewModel.Receivers.Where(o => o.Company == ChatTitle).FirstOrDefault().Brokerid;
                var message = new QuanYiOrderServerResponseClass { DataType = QuanYiServerBaseClass.DataTypeEnum.ChatMessage, ChatMessage = SelectedReply, BrokerID = brokerId, UserID = UserHelper.UserID };
                Messenger.Default.Send(message, MessageToken.SendChatMessage);
                AppLog.WriteInfo($"{UserHelper.NickName}发送消息{this.SelectedReply}至{ChatTitle}");

            }
            catch (Exception ex)
            {

            }
            finally
            {
                SelectedReply = null;
            }
        }
        /// <summary>
        /// 发送文字
        /// </summary>
        /// <param name="e"></param>
        //private void SendString(KeyEventArgs e)
        //{
        //    if (e.Key == Key.Enter)
        //    {
        //        if (string.IsNullOrEmpty(ChatString)) return;
        //        var info = new ChatInfoModel
        //        {
        //            Message = ChatString,
        //            SenderId = _id,
        //            Type = ChatMessageType.String,
        //            Role = ChatRoleType.Sender,
        //            NickName = UserHelper.NickName,
        //            ChatTitle = "测试1",
        //            CreateTime = DateTime.Now
        //        };
        //        var info2 = new ChatInfoModel
        //        {
        //            Message = ChatString,
        //            SenderId = _id,
        //            Type = ChatMessageType.String,
        //            Role = ChatRoleType.Receiver,
        //            NickName = UserHelper.NickName,
        //            ChatTitle = "测试2",
        //            CreateTime = DateTime.Now
        //        };
        //        ChatTitle = "测试111";
        //        ChatInfos.Add(info);
        //        ChatInfos.Add(info2);
        //        Messenger.Default.Send(info, MessageToken.SendChatMessage);
        //        ChatString = string.Empty;
        //    }
        //}

        /// <summary>
        /// 读信息（音频、图片）
        /// </summary>
        /// <param name="e"></param>
        private void ReadMessage(RoutedEventArgs e)
        {
            if (e.OriginalSource is FrameworkElement { Tag: ChatInfoModel info })
            {
                if (info.Type == ChatMessageType.Image)
                {
                    //{
                    //    new ImageBrowser(new Uri(info.Enclosure.ToString()))
                    //    {
                    //        Owner = WindowHelper.GetActiveWindow()
                    //    }.Show();
                }
                else if (info.Type == ChatMessageType.Audio)
                {
                    var player = new SoundPlayer(info.Enclosure.ToString());
                    player.PlaySync();
                }
            }
        }


        private void ReceiveMessage(ChatMessage info)
        {
            //if (_id.Equals(info.SenderId)) return;
            //info.Role = ChatRoleType.Sender;
            //ChatInfos.Add(info);
        }

        int i = 0;
        public void Refresh(string brokerName)
        {
            //ChatTitle = brokerName;

        }
        #endregion
    }
}
